package com.atomic.test.example.controller;

import com.atomic.test.example.entity.User;
import com.atomic.test.example.service.IUserService;
import com.atomic.test.example.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

import static com.atomic.test.example.common.Constants.CLIENT_SECRET;
import static com.atomic.test.example.common.Constants.USER_IN_SESSION;
import static com.atomic.test.example.common.ErrorCode.NO_PERMISSION;
import static com.atomic.test.example.common.ErrorCode.USER_USERLOGIN_ERROR;


/**
 * Created by DreamYao on 2017/1/24.
 */
@Controller
public class LoginController {

    @Autowired
    private IUserService userService;

    /**
     * 用户登录
     *
     * @param user
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<Void> loginPost(@RequestBody User user, HttpSession session) {
        String userName = user.getUserName();
        User queryUser = userService.getUserByUserName(userName);
        if (queryUser != null || queryUser.getUserName() != null) {
            User u = userService.login(user);
            if (u != null) {
                session.setAttribute(USER_IN_SESSION, u);
            } else {
                return new Result<>(USER_USERLOGIN_ERROR,"密码错误!");
            }
        }
        return new Result<>();
    }

    /**
     * 获取登录用户信息
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    public Result<User> getLoginUser(HttpSession session) {
        User user = (User) session.getAttribute("userInSession");
        if (user == null) {
            return new Result<>(NO_PERMISSION,"当前用户没有登录!");
        }
        user.setPassword(CLIENT_SECRET);
        return new Result<>(user);
    }
}
